<?php

/**
 * Class Demo
 */
class Demo
{
    private $host;
    /**
     * @var string AppId
     */
    private $appId;
    /**
     * @var string AppSecret
     */
    private $appSecret;
    /**
     * @var string 接口版本
     */
    private $version;
    /**
     * @var string 用户Token
     */
    private $token;

    /**
     * 初始化
     * @param string $appId AppId
     * @param string $appSecret AppSecret
     */
    public function __construct($appId, $appSecret)
    {
        $this->host = 'http://123.131.165.5';
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $this->version = '1.0.0';
        $this->token = 'xxxxxxxxxxxxxxxxx';
    }

    /**
     * 生成签名
     * @param array $params 参数列表
     * @return string
     */
    private function makeSign($params)
    {
        ksort($params);
        $tmpStr = '';
        foreach ($params as $k => $v) {
            if (!empty($v) || $v === '0') {
                $tmpStr .= $v;
            }
        }
        return md5($tmpStr . $this->appSecret);
    }

    /**
     * 生成接口地址URL
     * @param string $uri 接口地址
     * @return string
     */
    private function makeUrl($uri)
    {
        $params = [
            'app_id' => $this->appId,
            'nonce' => $this->random(),
            'timestamp' => time(),
            'version' => $this->version,
        ];
        return $this->host . $uri . '?' . http_build_query($params) . '&sign=' . $this->makeSign($params);
    }

    /**
     * 返回随机字符串
     * @param integer $len 随机字符串长度
     * @return string
     */
    private function random($len = 8)
    {
        $seed = '';
        $seed .= '1234567890';
        $seed .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $seed .= 'abcdefghijklmnopqrstuvwxyz';
        $str = '';
        $seed_l = strlen($seed);
        for ($i = 0; $i < $len; $i++) {
            $str .= substr($seed, rand(0, $seed_l - 1), 1);
        }
        return $str;
    }

    /**
     * 调用接口
     * @param string $uri 接口地址
     * @param array|string $data 接口参数数据
     * @return array
     */
    public function invoke($uri, $data)
    {
        $url = $this->makeUrl($uri);
        if (is_array($data)) {
            $data = json_encode($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'token: ' . $this->token,
        ]);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output, true);
    }
}
